
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * User: Administrator
 * Date: 2017/5/16
 * Time: 23:32
 */
public class Test {
public static void main2(String[] args) throws Exception {

    File privateKeyFile = new File("D:\\openssl-0.9.8h-1-bin\\private_key_pkcs8.pem");
    byte[] encodedKey = new byte[(int) privateKeyFile.length()];
    new FileInputStream(privateKeyFile).read(encodedKey);
    ByteBuffer keyBytes = new BASE64Decoder().decodeBufferToByteBuffer(encodedKey.toString());
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes.array());
    KeyFactory kf = KeyFactory.getInstance("RSA" );
    RSAPrivateKey pk = (RSAPrivateKey) kf.generatePrivate(privateKeySpec);
    System.out.println(new  BASE64Encoder().encode(pk.getEncoded()) );
}

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider())       ;
    File f = new File("D:\\openssl-0.9.8h-1-bin\\private-key-pkcs8.pem");
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();

    String temp = new String(keyBytes);
    String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", "");
    privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
    //System.out.println("Private key\n"+privKeyPEM);

    BASE64Decoder b64=new BASE64Decoder();
    byte[] decoded = b64.decodeBuffer(privKeyPEM);

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
    KeyFactory kf = KeyFactory.getInstance("ECDSA");
    PrivateKey pk= kf.generatePrivate(spec);
    System.out.println(new  BASE64Encoder().encode(pk.getEncoded()) );
}
}
